package com.xnyzc.lhy.order.service.impl.driver.wallet;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xnyzc.lhy.common.component.convert.DateToStringConverter;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.driver.wallet.EDriverWalletRecordType;
import com.xnyzc.lhy.common.penum.driver.wallet.EOaDWalletRecordListName;
import com.xnyzc.lhy.common.penum.wallet.EIsTransaction;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.order.entity.driver.wallet.OaDWallet;
import com.xnyzc.lhy.order.entity.driver.wallet.OaDWalletRecord;
import com.xnyzc.lhy.order.entity.order.OaDOrder;
import com.xnyzc.lhy.order.entity.vehicle.OaSysVehicle;
import com.xnyzc.lhy.order.mapper.driver.wallet.OaDWalletMapper;
import com.xnyzc.lhy.order.mapper.driver.wallet.OaDWalletRecordMapper;
import com.xnyzc.lhy.order.mapper.order.OaDOrderMapper;
import com.xnyzc.lhy.order.mapper.vehicle.OaSysVehicleMapper;
import com.xnyzc.lhy.order.service.driver.wallet.IOaDWalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 司机钱包表 服务实现类
 * </p>
 *
 * @author zhuyubin
 * @since 2019-08-12
 */
@Service
public class OaDWalletServiceImpl extends ServiceImpl<OaDWalletMapper, OaDWallet> implements IOaDWalletService {

    @Autowired
    private OaDWalletMapper oaDWalletMapper;
    @Autowired
    private OaDWalletRecordMapper oaDWalletRecordMapper;
    @Autowired
    private OaDOrderMapper oaDOrderMapper;
    @Autowired
    private OaSysVehicleMapper oaSysVehicleMapper;

    /**
     * 获取司机钱包
     * @param driverId 司机id
     * @param tag 租户
     * @return
     */
    @Override
    public Map<String, Object> getOaDWallet(Long driverId, String tag){
        OaDWallet oaDWallet = oaDWalletMapper.selectOne(
                Wrappers.<OaDWallet>lambdaQuery()
                        .eq(OaDWallet::getDriverId, driverId)
                        .eq(OaDWallet::getTag, tag)
        );
        if (CheckUtil.objIsEmpty(oaDWallet)){
            throw PangException.create(EErrorCode.unWallet);
        }
        BigDecimal walletBalance = oaDWallet.getWalletBalance();
        if (CheckUtil.objIsEmpty(walletBalance)){
            walletBalance = new BigDecimal(0);
        }
        Map<String, Object> result = new HashMap<>(16);
        result.put("walletBalance", walletBalance.toString());
        return result;
    }

    /**
     * 司机钱包列表
     * @param driverId 司机id
     * @param tag 租户
     * @param type 列表类型
     * @param current 当前页
     * @return
     */
    @Override
    public IPage selectOaDWalletRecordPage(Long driverId, String tag, Integer type, Long current){
        IPage<OaDWalletRecord> oaDWalletRecordPage = new Page<>();
        oaDWalletRecordPage.setCurrent(current);
        LambdaQueryWrapper<OaDWalletRecord> eq = Wrappers.<OaDWalletRecord>lambdaQuery().eq(OaDWalletRecord::getDriverId, driverId).eq(OaDWalletRecord::getTag, tag).orderByDesc(OaDWalletRecord::getTransactionTime);
        // 收入
        if (type.equals(1)){
            eq.in(OaDWalletRecord::getRecordType,
                    EDriverWalletRecordType.income.getValue(),
                    EDriverWalletRecordType.weChatIncome.getValue(),
                    EDriverWalletRecordType.alipayIncome.getValue()
            );
        }
        // 支出
        else if (type.equals(2)){
            eq.in(OaDWalletRecord::getRecordType,
                    EDriverWalletRecordType.expenditure.getValue(),
                    EDriverWalletRecordType.weChatExpenditure.getValue(),
                    EDriverWalletRecordType.alipayExpenditure.getValue()
            );
        }
        // 钱包
        IPage<OaDWalletRecord> oaDWalletRecordIPage = oaDWalletRecordMapper.selectPage(oaDWalletRecordPage, eq);
        List<Map<String, Object>> list = new ArrayList<>();
        for (OaDWalletRecord oaDWalletRecord : oaDWalletRecordIPage.getRecords()) {
            Map<String, Object> map = new HashMap<>(16);
            map.put("transactionTime", new DateToStringConverter().convert(oaDWalletRecord.getTransactionTime()));
            map.put("amountRemark", oaDWalletRecord.getAmountRemark());
            map.put("vehNo", "");
            String orderNo = oaDWalletRecord.getOrderNo();
            if (CheckUtil.objIsNotEmpty(orderNo)){
                OaDOrder oaDOrder = oaDOrderMapper.selectOne(Wrappers.<OaDOrder>lambdaQuery().eq(OaDOrder::getDriverId, driverId).eq(OaDOrder::getOrderNo, orderNo));
                if (CheckUtil.objIsNotEmpty(oaDOrder)){
                    Long vehicleId = oaDOrder.getVehicleId();
                    OaSysVehicle oaSysVehicle = oaSysVehicleMapper.selectOne(Wrappers.<OaSysVehicle>lambdaQuery().eq(OaSysVehicle::getVehicleId, vehicleId).eq(OaSysVehicle::getTag, tag));
                    if (CheckUtil.objIsNotEmpty(oaSysVehicle)){
                        map.put("vehNo", oaSysVehicle.getVehNo());
                    }
                }
            }
            // 收入
            if (EDriverWalletRecordType.findById(oaDWalletRecord.getRecordType()).getType().equals(0)){
                map.put("amount", String.format("+ %s", oaDWalletRecord.getAmount()));
                map.put("recordType", EDriverWalletRecordType.income.getType());
            }
            // 支出
            else if (EDriverWalletRecordType.findById(oaDWalletRecord.getRecordType()).getType().equals(1)){
                map.put("amount", String.format("- %s", oaDWalletRecord.getAmount()));
                map.put("recordType", EDriverWalletRecordType.expenditure.getType());
            }
            // 其他
            else {
                map.put("amount", oaDWalletRecord.getAmount());
                map.put("recordType", EDriverWalletRecordType.withdraw.getType());
            }
            map.put("recordId", oaDWalletRecord.getRecordId().toString());
            list.add(map);
        }
        IPage page = new Page();
        page.setRecords(list);
        page.setCurrent(current);
        page.setPages(oaDWalletRecordIPage.getPages());
        page.setSize(oaDWalletRecordIPage.getSize());
        page.setTotal(oaDWalletRecordIPage.getTotal());
        return page;
    }

    /**
     * 钱包详情
     * @param driverId 司机id
     * @param tag 租户
     * @param recordId 列表id
     * @return
     */
    @Override
    public Map<String, Object> getOaDWalletRecord(Long driverId, String tag, Long recordId){
        Map<String, Object> result = new HashMap<>(16);
        List<Map<String, Object>> list = new ArrayList<>();
        OaDWalletRecord oaDWalletRecord = oaDWalletRecordMapper.selectOne(Wrappers.<OaDWalletRecord>lambdaQuery().eq(OaDWalletRecord::getDriverId, driverId).eq(OaDWalletRecord::getTag, tag).eq(OaDWalletRecord::getRecordId, recordId));
        if (CheckUtil.objIsEmpty(oaDWalletRecord)){
            throw PangException.create(EErrorCode.unDetails);
        }
        EDriverWalletRecordType eDriverWalletRecordType = EDriverWalletRecordType.findById(oaDWalletRecord.getRecordType());

        result.put("vehNo", "");
        String orderNo = oaDWalletRecord.getOrderNo();
        if (CheckUtil.objIsNotEmpty(orderNo)){
            OaDOrder oaDOrder = oaDOrderMapper.selectOne(Wrappers.<OaDOrder>lambdaQuery().eq(OaDOrder::getDriverId, driverId).eq(OaDOrder::getOrderNo, orderNo));
            if (CheckUtil.objIsNotEmpty(oaDOrder)){
                Long vehicleId = oaDOrder.getVehicleId();
                OaSysVehicle oaSysVehicle = oaSysVehicleMapper.selectOne(Wrappers.<OaSysVehicle>lambdaQuery().eq(OaSysVehicle::getVehicleId, vehicleId).eq(OaSysVehicle::getTag, tag));
                if (CheckUtil.objIsNotEmpty(oaSysVehicle)){
                    list = this.addResult(EOaDWalletRecordListName.costDesc.getName(), String.format("%s %s", oaSysVehicle.getVehNo(), oaDWalletRecord.getAmountRemark()), list);
                }
            }
        }

        list = this.addResult(EOaDWalletRecordListName.sort.getName(), eDriverWalletRecordType.getTypeMsg(), list);
        list = this.addResult(EOaDWalletRecordListName.time.getName(), new DateToStringConverter().convert(oaDWalletRecord.getTransactionTime()), list);
        list = this.addResult(EOaDWalletRecordListName.payType.getName(), eDriverWalletRecordType.getDesc(), list);
        list = this.addResult(EOaDWalletRecordListName.orderNo.getName(), oaDWalletRecord.getOrderNo(), list);
        result.put("list", list);
        result.put("isTransaction", EIsTransaction.findById(oaDWalletRecord.getIsTransaction()).getDesc());
        result.put("transactionAddress", oaDWalletRecord.getTransactionAddress());
        // 收入
        if (eDriverWalletRecordType.getType().equals(0)){
            result.put("amount", String.format("+ %s", oaDWalletRecord.getAmount()));
        }
        // 支出
        else if (eDriverWalletRecordType.getType().equals(1)){
            result.put("amount", String.format("- %s", oaDWalletRecord.getAmount()));
        }
        // 其他
        else {
            result.put("amount", oaDWalletRecord.getAmount().toString());
        }
        return result;
    }

    /**
     * 拼接出参
     * @param name
     * @param value
     * @param result
     * @return
     */
    private List<Map<String, Object>> addResult(String name, String value, List<Map<String, Object>> result){
        Map<String, Object> map = new HashMap<>(16);
        map.put("name", name);
        map.put("value", value);
        result.add(map);
        return result;
    }
}
